<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-button type="primary" @click="generateFlag">{{ $t('flag.generate_flag') }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="exportFlagDialogVisible = true">{{ $t('flag.export_flag') }}</el-button>
      </el-form-item>
      <el-form-item></el-form-item>
      <el-form-item :label="$t('flag.round')">
        <el-input-number v-model="round" controls-position="right" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item :label="$t('flag.team')">
        <el-select v-model="team" :placeholder="$t('flag.select_team')">
          <el-option
              v-for="item in teamList"
              :key="item.ID"
              :label="item.Name"
              :value="item.ID">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('flag.challenge')">
        <el-select v-model="challenge" :placeholder="$t('flag.select_challenge')">
          <el-option
              v-for="item in challengeList"
              :key="item.ID"
              :label="item.Title"
              :value="item.ID">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" round @click="()=> {page = 1; getFlags()}">
          {{ $t('flag.filter') }}
        </el-button>
        <el-button round @click="cleanFilter"> {{ $t('flag.clean_filter') }}</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="flagList" style="width: 100%" stripe v-loading="flagList === null">
      <el-table-column width="80" prop="ID" label="ID"/>
      <el-table-column width="80" prop="TeamID" :label="$t('flag.team')"/>
      <el-table-column width="80" prop="ChallengeID" :label="$t('flag.challenge')"/>
      <el-table-column width="80" prop="GameBoxID" :label="$t('flag.gamebox')"/>
      <el-table-column width="80" prop="Round" :label="$t('flag.round')"/>
      <el-table-column prop="Flag" :label="$t('flag.flag')"/>
    </el-table>
    <br>
    <el-pagination style="text-align:center" background layout="prev, pager, next" :total="total" :page-size="per"
                   @current-change="(p)=>{page = p; getFlags()}"></el-pagination>

    <!-- Export -->
    <el-dialog :title="$t('flag.export_flag')" v-model="exportFlagDialogVisible">
      <el-form label-width="120px">
        <el-form-item :label="$t('challenge.title')">
          <el-select v-model="exportChallengeID">
            <el-option
                v-for="challenge in challengeList"
                :key="challenge.ID"
                :label="challenge.Title"
                :value="challenge.ID">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="exportFlag">{{ $t('general.export') }}</el-button>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getCurrentInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import utils from '@/utils.js'

const { proxy } = getCurrentInstance()
const { t } = useI18n()

const page = ref(1)
const per = ref(15)

const total = ref(0)
const flagList = ref(null)

const teamList = ref([])
const challengeList = ref([])
const exportFlagDialogVisible = ref(false)
const exportChallengeID = ref(null)

const totalRound = ref(0)

    // Filter
const round = ref(0)
const team = ref(null)
const challenge = ref(null)
  

onMounted(() => {
    getTotalRound()
    getTeams()
    getFlags()
    getChallenges()
  })

  
function getTeams() {
      utils.GET("/manager/teams").then(res => {
        teamList.value = res
      }).catch(err => proxy.$message.error(err))
    }

function getChallenges() {
      utils.GET("/manager/challenges").then(res => {
        challengeList.value = res
      }).catch(err => proxy.$message.error(err))
    }

function getTotalRound() {
      utils.GET('/time').then(res => {
        totalRound.value = res.TotalRound
      }).catch(err => proxy.$message({message: err, type: 'error'}))
    }

function getFlags() {
      let _team = team.value || 0
      let _challenge = challenge.value || 0

      utils.GET(`/manager/flags?per=${per.value}&page=${page.value}&round=${round.value}&team=${_team}&challenge=${_challenge}`).then(res => {
        flagList.value = res.array
        total.value = res.total
      }).catch(err => proxy.$message({message: err, type: 'error'}))
    }

function cleanFilter() {
      round.value = 0
      team.value = null
      challenge.value = null
      page.value = 1
      getFlags()
    }

function generateFlag() {
      proxy.$confirm(t('flag.generate_flag_confirm'), t('flag.confirm'), {
        confirmButtonText: t('general.apply'),
        cancelButtonText: t('general.cancel'),
        type: 'warning'
      }).then(() => {
        utils.POST('/manager/flag/generate').then(res => {
          getFlags()
          proxy.$message({message: res, type: 'success'})
        }).catch(err => this.$message({message: err, type: 'error'}))
      })
    }

function exportFlag() {
      utils.GET("/manager/flag/export?id=" + exportChallengeID.value).then(res => {
        let blob = new Blob([JSON.stringify(res)], {type: 'text/plain'})
        let downloadElement = document.createElement("a")
        let href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = name
        downloadElement.click()
        window.URL.revokeObjectURL(href)
      }).catch(err => proxy.$message({message: err, type: 'error'}))
    }
</script>

<style scoped>

</style>